import Vue from 'vue';
import Router from 'vue-router';
import NotFoundComponent from '@/components/NotFoundComponent';
import common from '@/common/common';

Vue.use(Router);

const requireAuth = function (to, from, next) {
  const isLogin = common.getToken();
  common.vueRouter = {next, to};
  // const isLs = common.getLocalStorage();
  if ((!isLogin && from.path !== '/login')) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    });
  } else {
    common.params = {
      token:common.getToken() + common.isDeviceAllow()
    };
    next();
  }
};

const getComponent = page => () => import(`@/pages/${page}`);
const vueRouter = new Router({
  mode: 'hash', //history
  routes: [
    {
      path: '/login',
      component: getComponent('login'),
      meta: { title: '登录' }
    },
    {
      path: '/logout',
      component: () => import('./components/log-out')
    },
    {
      path: '/register',
      component: getComponent('register'),
      meta: { title: '注册' }
    },
    {
      path: '/contact',
      component: getComponent('contact'),
      meta: { title: '联系我们' }
    },
    {
      path: '/',
      component: () => import('./pages'),
      children: [
        {
          path: '',
          component: getComponent('home'),
          meta: { title: '首页' },
          beforeEnter: requireAuth.bind(this)
        }
      ]
    },
    { path: '*', component: NotFoundComponent,  meta: { title: '页面找不到!' }}
  ]
});

var indexScrollTop = 0;
vueRouter.beforeEach((route, redirect, next) => {
  if (route.path !== '/') {
    indexScrollTop = document.body.scrollTop;
  }
  document.title = route.meta.title || document.title;
  next();
});

vueRouter.afterEach(route => {
  if (vueRouter.vueConstruct) {
    vueRouter.vueConstruct.$store.commit('home/SET_VALUE', {
      title: route.meta.title
    });
  }
  if (route.path !== '/') {
    document.body.scrollTop = 0;
    if (vueRouter.vueConstruct) {
      vueRouter.vueConstruct.$store.commit('home/SET_VALUE', {
        isBack: true
      });
    }
  } else {
    Vue.nextTick(() => {
      document.body.scrollTop = indexScrollTop;
    });
    if (vueRouter.vueConstruct) {
      vueRouter.vueConstruct.$store.commit('home/SET_VALUE', {
        isBack: false
      });
    }
  }
});

export default vueRouter;
